import 'package:flutter/material.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/msg/drive_timerange_list.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../base/base_state.dart';
import '../../base/full_base_page.dart';
import '../../http/api.dart';
import '../../http/http_utils.dart';
import '../../res/w_constant.dart';
import '../../res/w_dimens.dart';
import '../../utils/router_helper.dart';
import '../../widget/custom_search.dart';
import '../../widget/custom_tab.dart';
import '../../widget/status_btn.dart';
import '../../widget/w_line.dart';
import '../../widget/w_list_view.dart';
import 'notice_detail_page.dart';

class NoticeMsgPage extends StatefulWidget {
  const NoticeMsgPage({super.key});

  @override
  BaseState<NoticeMsgPage> createState() => _NoticeMsgPageState();
}

class _NoticeMsgPageState extends BaseState<NoticeMsgPage> {
  //设置tab列表项
  List<Map> tabs = [
    {"title": "未读", "count": 0},
    {"title": "已读", "count": 0},
  ];

  // 假设消息数据，需要根据实际情况进行填充
  List unreadMessagesListRow = [];

  int selectedIndex = 0; // 当前选中的标签索引，初始为未读
  //当前消息
  List currentMsgList = [];
  var mCurrentStatus;
  int mPage = 0;
  String keyword = "";

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "通知公告",
        child: Column(
          children: <Widget>[
            CustomSearch(
              hintText: "通告主题/通告编号/主要内容",
              showSort: false,
              onTextChange: (text) {
                keyword = text;
                mPage = 1;
                showLoading();
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            CustomTab(
              tabList: tabs,
              tabClick: (index) {
                selectedIndex = index;
                mPage = 1;
                showLoading();
                fetchDataList();
              },
            ),
            Expanded(
              child: WListView(
                padding: EdgeInsets.symmetric(vertical: 10.px),
                itemBuilder: _noticeMsgItem,
                getDataList: (currentState, page) {
                  mCurrentStatus = currentState;
                  mPage = page;
                  fetchDataList();
                },
              ),
            ),
          ],
        ));
  }

  Widget _noticeMsgItem(context, index, currentMsgList) {
    Map message = currentMsgList[index];
    return GestureDetector(
        onTap: () {
          //跳转到公告正文详情
          RouteHelper.pushWidget(context,
                  NoticeDetailPage(noticeId: message["notificationId"]))
              .then((isCancel) {
            if (selectedIndex == 0) {
              showLoading();
              fetchDataList();
            }

            // if (isCancel == null) {
            //
            // }
          });
        },
        child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(
            left: 15.px,
            right: 15.px,
            bottom: 10.px,
          ),
          padding: EdgeInsets.only(top: 10.px, bottom: 10.px, right: 10.px),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.px),
              color: Colors.white,
              boxShadow: const [
                BoxShadow(
                    //线框阴影线条
                    color: WColors.border,
                    offset: Offset(0, 1),
                    blurRadius: 2)
              ]),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                        child: Row(
                      children: [
                        WLine(
                          width: 4.px,
                          height: 16.px,
                          color: WColors.primaryColor,
                          marginRight: 10.px,
                        ),
                        Flexible(
                            child: WText(
                                StringUtils.safeGetValue(
                                        message['notificationTitle'],placeHolder: "-"),
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: WDimens.tsLarge,
                                    color: WColors.mainTextColor,
                                    fontWeight: FontWeight.bold))),
                        StatusBtn(
                          margin: EdgeInsets.only(left: 10.px),
                          height: 28.px,
                          width: 68.px,
                          color: WColors.border,
                          fontColor: WColors.mainTextColor,
                          text: StringUtils.safeGetValue(
                              message['notificationType']),
                          isItemBtn: true,
                        ),
                      ],
                    )),
                    SizedBox(
                      width: 20.px,
                    ),
                    StatusBtn(
                      width: 56.px,
                      height: 28.px,
                      color: message["urgency"] == "紧急"
                          ? WColors.redMain
                          : message["urgency"] == "低"
                              ? WColors.green
                              : WColors.orange,
                      text: StringUtils.safeGetValue(message["urgency"]),
                      isItemBtn: true,
                      isTag: true,
                    ),
                  ],
                ),
                WLine(
                  height: 0.5.px,
                  marginTop: 10.px,
                  marginBottom: 10.px,
                ),
                Padding(
                    padding: EdgeInsets.only(left: 10.px),
                    child: WText(
                        StringUtils.safeGetValue(message['notificationContent'],
                            placeHolder: "-"),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor,
                        ))),
                DriveTimeStepper(
                    startTime: message['timing'],
                    endTime: StringUtils.safeGetValue(message['endTime']) == ""
                        ? "-"
                        : StringUtils.safeGetValue(message['endTime'])),
                SizedBox(height: 10.px),
              ]),
        ));
  }

  void fetchDataList() {
    HttpUtils()
        .get(
            "${Api.getNoticeMessageList}?userId=${WConstant().userInfo.userId}&status=${selectedIndex == 0 ? "未读" : "已读"}&pageNum=${mPage}&limit=20&notificationContent=${keyword}")
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List list = value.data["list"];

        ///不容易，必须得这样写放在setState里异步，在http请求执行获取到数据后更新才有用,然后还必须得放在if里不然一上拉就清空了
        if (mPage == 1) {
          tabs[0]["count"] = value.data["unreadNum"];
          tabs[1]["count"] = value.data["readNum"];
          setState(() {});
          currentMsgList.clear();
        }
        currentMsgList.addAll(list);
        mCurrentStatus.onRefreshData(list, mPage);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }
}
